package cz.boxdesign.library.entity.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cz.boxdesign.library.common.dao.CommonDao;
import cz.boxdesign.library.common.dao.DatabaseOperationException;
import cz.boxdesign.library.entity.Book;
import cz.boxdesign.library.entity.Department;
import cz.boxdesign.library.entity.Publisher;
import cz.boxdesign.library.entity.dao.query.KnihaSqlQuery;

/**
 * @author jlattenberk
 *
 */
@Component(value = "knihaDao")
public class BookDaoImpl extends EntityDaoAbstract<Book, KnihaSqlQuery> {

  @Autowired
  CommonDao commonDao;

  @Override
  void getEntityList(List<Book> result, ResultSet rs) throws SQLException {
    while (rs.next()) {
      Book k = new Book();
      k.setId(rs.getInt("ID"));
      k.setNazev(rs.getString("NAZEV_K"));
      k.setPocetKnih(rs.getInt("POCET_K"));
      k.setRokVydani(rs.getString("VYDANI_K"));
      try {
        k.setNakladatelstvi((Publisher) this.commonDao.getDao(Publisher.class).getById(rs.getInt("ID_N")));
        k.setOddeleni((Department) this.commonDao.getDao(Department.class).getById(rs.getInt("ID_O")));
      } catch (DatabaseOperationException e) {
        e.printStackTrace();
      }
      result.add(k);
    }
  }

  @Override
  String getSqlQuery(int queryValue) {
    return KnihaSqlQuery.getByValue(queryValue).getQuery();
  }

  @Override
  void fillStatement(Book entity, int queryValue, PreparedStatement ps) throws SQLException {
    KnihaSqlQuery clause = KnihaSqlQuery.getByValue(queryValue);
    switch (clause) {
      case UPDATE: {
        ps.setInt(6, entity.getId());
      }
      case INSERT: {
        ps.setString(1, entity.getNazev());
        ps.setInt(2, entity.getPocetKnih());
        ps.setString(3, entity.getRokVydani());
        ps.setInt(5, entity.getNakladatelstvi().getId());
        ps.setInt(4, entity.getOddeleni().getId());
        break;
      }
      case DELETE: {
        ps.setInt(1, entity.getId());
        break;
      }
      default:
        throw new IllegalArgumentException();
    }
  }

}
